package com.example.demo.demos.web.comment.exception;

import com.example.demo.demos.web.comment.response.JsonResult;
import com.example.demo.demos.web.comment.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * ControllerAdvice注解:
 *  1.将此类标识为全句异常处理器,处理由控制器抛出的异常;
 *  2.如果控制器抛出异常后，框架会先检查是否定义了全局异常处理器;
 *   2.1 未定义:Spring MVC默认的异常处理机制[不友好];
 *   2.2 定义了:则到全局异常处理器找到对应的异常处理方法处理异常;
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * ExceptionHandler注解:
     * @param ex 异常对象
     * @return JsonResult
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("IllegalArgumentException:" + data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException:" + data);
        return JsonResult.fail(data);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
//    @ExceptionHandler
//    public JsonResult doThrowable(Throwable ex){
//        String data = ex.getMessage();
//        log.error("Throwable:" + data);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
//    }
}
